package com.atm.bulksms.util;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.PhoneLookup;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.atm.bulksms.ContactChooser;
import com.atm.bulksms.GroupListActivity;
import com.atm.bulksms.R;
import com.atm.bulksms.ScheduleActivity;
import com.atm.bulksms.data.ContactItem;
import com.atm.bulksms.data.BulkSMSData.GroupData;

public class Utils {

	private static Hashtable<Integer, ContactItem> selectedContacts = new Hashtable<Integer, ContactItem>(2);
	private static Hashtable<String, Vector<ContactItem>> selectedGroupContacts = new Hashtable<String, Vector<ContactItem>>(2);
	//private static Vector<String> selectedGroups = new Vector<String>();
	public static void setSelectedContacts(Hashtable<Integer, ContactItem> contacts){
		selectedContacts = contacts;
	}
	
	public static Hashtable<Integer, ContactItem> getSelectedContacts(){
		return selectedContacts ;
	}
	
	public static boolean hasContact(int id){
		System.out.println("selectedContacts "+selectedContacts+" id "+id);
		boolean b = selectedContacts.get(id) != null; 
		//System.out.println(" Returnig "+b);
		return b;
	}
	public static boolean hasContact(int id, String name){
		System.out.println("selectedContacts "+selectedContacts+" id "+id);
		boolean idPresent = selectedContacts.get(id) != null; 
		//if(!idPresent) 
		//	idPresent = isContactInSelectedGroup(name);
		//System.out.println(" Returnig "+b);
		return idPresent;
	}

	public static void addContact(int id, ContactItem item) {
		selectedContacts.put(id, item);
	}
	
	public static void removeContact(int id) {
		System.out.println("Before : "+selectedContacts);
		selectedContacts.remove(id);
		System.out.println("id removed "+id);
		System.out.println("After : "+selectedContacts);
	}
	public static void removeContact(int id, ContactItem item) {
		System.out.println("Before : "+selectedContacts);
		if(selectedContacts.remove(id) == null){ // not available in selected contacts - need to search in selected groups
			System.out.println("ID not stored .. need to check in groups");
			String groupName = getGroupName(item.getNumberList().elementAt(0));
			
			System.out.println("groupName : "+groupName);
			if(groupName != null){
				// transfer the contacts to selected Contacts
				Vector<ContactItem> groupContacts = getSelectedGroupContacts(groupName);
				System.out.println("groupContacts :: "+groupContacts+" item :: "+item);
				boolean b = groupContacts.remove(item);
				System.out.println(" removed "+b);
				for (ContactItem contactItem : groupContacts) {
					addContact(contactItem.getId(), contactItem);
				}
				// remove the group from selection
				removeSelectedGroup(groupName);
			}
		}
		System.out.println("id removed "+id);
		System.out.println("After : "+selectedContacts+" and SelectedGroups :: "+selectedGroupContacts);
	}

	public static void removeAllContacts() {
		selectedContacts.clear();
		selectedGroupContacts.clear();
	}
	
	public static ContactItem getContactItem(int id){
		return selectedContacts.get(id);
	}
	
	public static String getContactName(Context ctx, String phoneNumber) {
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
		Cursor c =  ctx.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
		if(c != null && c.getCount() > 0){
			c.moveToFirst();
		String name = c.getString(c.getColumnIndex(PhoneLookup.DISPLAY_NAME));
		System.out.println(" name : "+name);
		c.close();
		return name+"\n"+phoneNumber;
		}
		return phoneNumber;
	}
	
	public static int getContactId(Context ctx, String phoneNumber) {
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
		Cursor c =  ctx.getContentResolver().query(uri, new String[]{PhoneLookup._ID}, null, null, null);
		int id = -1;
		if(c != null && c.getCount() > 0){
			c.moveToFirst();
		id = c.getInt(c.getColumnIndex(PhoneLookup._ID));
		System.out.println(" id : "+id);
		c.close();
		}
		return id;
	}

	public static Dialog getDialog(Context ctx, String title, String message) {
		AlertDialog.Builder alert = new AlertDialog.Builder(ctx);
		alert.setTitle(title);
		alert.setMessage(message);
		alert.setNeutralButton("Ok", new DialogInterface.OnClickListener(){
		
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		return alert.create();
	}

	private static Cursor cursor;
	public static Cursor getCursor() {
		return cursor;
	}

	public static void setCursor(Cursor c) {
		// TODO Auto-generated method stub
		cursor = c;
	}
	
	public static Dialog getContactSourceDialog(final Activity ctx){
		AlertDialog.Builder pickList = new AlertDialog.Builder(ctx);
		pickList.setTitle("Add Contact from");
		pickList.setItems(new String[]{"Contact List", "Groups"}, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		    	if(item == 0){
		    		Intent pickContact = new Intent(ctx, ContactChooser.class);
		    		ctx.startActivity(pickContact);
		    	}else if(item == 1){
		    		Intent pickContact = new Intent(ctx, GroupListActivity.class);
		    		pickContact.putExtra(Constants.LIST_TYPE, Constants.LIST_TYPE_GROUP_SELECT);
		    		ctx.startActivityForResult(pickContact, 0);
		    	}
		    }
		});
		return pickList.create();
	}
	public static Enumeration<String> getSelectdGroupNames() {
		return selectedGroupContacts.keys();		
	}
	/*public static void addGroup(String selectedGroupName) {
		if(selectedGroups.contains(selectedGroupName)) return;
		selectedGroups.add(selectedGroupName);		
	}
	public static Vector<String> getSelectdGroups() {
		return selectedGroups;		
	}
	public static void removeAllGroups(){
		selectedGroups.removeAllElements();
	}

	public static void removeGroup(String name) {
		selectedGroups.remove(name);
		// remove contacts from group..
		
	}
	public static void removeGroup(String name, Context ctx) {
		selectedGroups.remove(name);
		// remove contacts from group..
		Cursor c = ctx.getContentResolver().query(GroupData.CONTENT_URI, null, GroupData.GROUP_NAME+"=\""+name+"\"", null, null);
		while(c.moveToNext()){
			selectedContacts.remove(getContactId(ctx, c.getString(c.getColumnIndex(GroupData.PHONE_NUMBER))));
		}
		c.close();
	}*/

	public static void addContactInGroup(String selectedGroupName,
			ContactItem item) {
		Vector<ContactItem> items = selectedGroupContacts.get(selectedGroupName);
		if(items == null) items = new Vector<ContactItem>();
		items.add(item);
		selectedGroupContacts.put(selectedGroupName, items);
		System.out.println("selectedGroupContacts "+selectedGroupContacts+" items "+items.size());
	}
	
	public static Vector<ContactItem> getSelectedGroupContacts(String groupName){
		return selectedGroupContacts.get(groupName);
	}
	public static Hashtable<String, Vector<ContactItem>> getSelectedGroups(){
		return selectedGroupContacts;
	}
	public static void removeAllSelectedGroups(){
		selectedGroupContacts.clear();
	}
	public static void removeSelectedGroup(String groupName){
		selectedGroupContacts.remove(groupName);
	}
	public static  boolean isContactInSelectedGroup(String name) {
		Enumeration<String> groups = Utils.getSelectdGroupNames();
		while (groups.hasMoreElements()) {
			Vector<ContactItem> contacts = Utils.getSelectedGroupContacts(groups.nextElement());
			for (int i = 0; i < contacts.size(); i++) {
				ContactItem item = contacts.elementAt(i);
				if(item.getName().equals(name))return true;
			}
		}
		return false;
	}
	public static  boolean isContactInSelectedGroup(String name, String number) {
		Enumeration<String> groups = Utils.getSelectdGroupNames();
		while (groups.hasMoreElements()) {
			Vector<ContactItem> contacts = Utils.getSelectedGroupContacts(groups.nextElement());
			for (int i = 0; i < contacts.size(); i++) {
				ContactItem item = contacts.elementAt(i);
				if(item.getName().equals(name) && item.hasContact(number))return true;
			}
		}
		return false;
	}
	
	private static  String getGroupName(String number) {
		Enumeration<String> groups = Utils.getSelectdGroupNames();
		while (groups.hasMoreElements()) {
			String name = groups.nextElement();
			Vector<ContactItem> contacts = Utils.getSelectedGroupContacts(name);
			for (int i = 0; i < contacts.size(); i++) {
				ContactItem item = contacts.elementAt(i);
				if(item.hasContact(number))return name;
			}
		}
		return null;
	}
	
	public static int getSelectedRecipientCount(){
		int count = 0;
		Enumeration<ContactItem> items = selectedContacts.elements();
		while(items.hasMoreElements()){
			ContactItem item = items.nextElement();
			count += item.getNumberList().size();
		}
		Enumeration<Vector<ContactItem>> groupItems = selectedGroupContacts.elements();
		while(groupItems.hasMoreElements()){
			Vector<ContactItem> contactItems = groupItems.nextElement();
			for (ContactItem contactItem : contactItems) {
				count += contactItem.getNumberList().size();
			}
		}
		return count;
	}

	public static void showDialog(Context ctx, int dialogMessageId, String title, String message) {
		
	}
	
	public static String getRecipientsDetails(){
		StringBuffer str = new StringBuffer();
		
		Enumeration<ContactItem> items = selectedContacts.elements();
		while(items.hasMoreElements()){
			ContactItem item = items.nextElement();
			str.append(item.getNumberDetails());
		}
		Enumeration<Vector<ContactItem>> groupItems = selectedGroupContacts.elements();
		while(groupItems.hasMoreElements()){
			Vector<ContactItem> contactItems = groupItems.nextElement();
			for (ContactItem contactItem : contactItems) {
				str.append(contactItem.getNumberDetails());
			}
		}
		str.deleteCharAt(str.length() - 1);
		return str.toString();
		
		
	}

	public static Dialog createDialog(Context ctx, String title, String message) {
		AlertDialog.Builder d = new AlertDialog.Builder(ctx);
		d.setTitle(title);
		d.setMessage(message);
		
		return d.create();
	}

	
	
}
